package com.meiyuetao.myt.job;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.ctx.DynamicConfigService;
import lab.s2jh.schedule.BaseQuartzJobBean;

import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.sale.entity.SaleDelivery;
import com.meiyuetao.myt.sale.service.SaleDeliveryService;

public class AutoAssignTimeOutSaleDeliveryJob extends BaseQuartzJobBean {
    private static Logger logger = LoggerFactory.getLogger(AutoAssignTimeOutSaleDeliveryJob.class);

    protected void executeInternalBiz(JobExecutionContext context) {
        SaleDeliveryService saleDeliveryService = this.getSpringBean(SaleDeliveryService.class);
        DynamicConfigService dynamicConfigService = this.getSpringBean(DynamicConfigService.class);

        // 自动指派长期为接单处理
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        // 审核通过的
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NN, "auditDate", true));
        // 没有红冲的
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NU, "redwordDate", true));
        // 已指派代理商
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NN, "agentPartner", true));
        // 未接单
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NU, "agentAcceptDate", true));

        // 最大等待小时数
        String maxWaitHours = dynamicConfigService.getString("cfg.agent.sale.delivery.max.wait.hours", "24");
        int maxWaitHoursInt = Integer.parseInt(maxWaitHours);
        // 反推出指派时间
        Calendar reversersDate = Calendar.getInstance();
        reversersDate.setTime(new Date());
        reversersDate.set(Calendar.HOUR_OF_DAY, reversersDate.get(Calendar.HOUR_OF_DAY) - maxWaitHoursInt);

        // 在reversersDate之前指派的销售单
        groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.LT, "agentAssignDate", reversersDate.getTime()));
        List<SaleDelivery> saleDeliverys = saleDeliveryService.findByFilters(groupPropertyFilter);
        if (!CollectionUtils.isEmpty(saleDeliverys)) {
            for (SaleDelivery saleDelivery : saleDeliverys) {
                Partner parent = saleDelivery.getAgentPartner().getParent();
                if (parent != null) {
                    saleDelivery.setAgentPartner(parent);// 退回上级
                    saleDelivery.setAgentAssignDate(new Date());// 指派时间改为当前时间
                    saleDeliveryService.doSave(saleDelivery);
                    logger.info("[ " + saleDelivery.getDisplay() + " ]长期未被接收，已自动退回。");
                }
            }
        }
    }
}